# encoding: utf-8
import pathlib

from automatic.file.FolderCompareListener import FolderCompareListener
from automatic.file.FolderCompareResultType import FOLDER_COMPARE_RESULT_TYPE_DIFFERENT_FILE, \
    FOLDER_COMPARE_RESULT_TYPE_NEW_ONLY


class FolderCompareWindowsGenerator(FolderCompareListener):

    file_object = None

    def __init__(self, output_path, new_dir, old_dir):
        self.new_dir = new_dir
        self.old_dir = old_dir
        self.output_path = output_path

    def begin(self):
        try:
            self.file_object = open(self.output_path, "w", newline="\r\n")
            print("set new_root_dir=%s" % self.new_dir, file=self.file_object)
            print("set old_root_dir=%s" % self.old_dir, file=self.file_object)
        except OSError as e:
            print(str(e))

    def end(self):
        if self.file_object:
            self.file_object.close()

    def process(self, result_type, new_root_dir, new_relative_dir, old_root_dir, old_relative_dir, file_name):
        # print("result_type %d, %s found in %s and %s" % (result_type, file_name, new_relative_dir,
        #                                            old_relative_dir))
        new_sub_path = (new_relative_dir+"\\"+file_name)if len(new_relative_dir) else file_name
        old_sub_path = (old_relative_dir + "\\" + file_name) if len(old_relative_dir) else file_name

        if result_type == FOLDER_COMPARE_RESULT_TYPE_DIFFERENT_FILE:
            print("copy /Y \"%%new_root_dir%%%s\" \"%%old_root_dir%%%s\"" % (
                new_sub_path, old_sub_path), file=self.file_object)
        elif result_type == FOLDER_COMPARE_RESULT_TYPE_NEW_ONLY:
            new_path = pathlib.Path(new_root_dir + new_sub_path)
            if new_path.is_dir():
                print("xcopy /I /E \"%%new_root_dir%%%s\" \"%%old_root_dir%%%s\"" % (
                    new_sub_path, old_sub_path), file=self.file_object)
            else:
                print("copy /Y \"%%new_root_dir%%%s\" \"%%old_root_dir%%%s\"" % (
                    new_sub_path, old_sub_path), file=self.file_object)
        else:
            print("del /S/Q \"%%old_root_dir%%%s\"" % old_sub_path, file=self.file_object)